package com.dd.ent.car.common.player;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.text.TextUtils;
import android.util.SparseArray;

import com.dd.ent.car.AppContext;
import com.dd.ent.car.common.util.NetworkHelper;
import com.pp.ent.base.log.MLog;

import java.util.ArrayList;
import java.util.List;

/**
 * Author:LiuJianSheng
 * Date:2016/6/14
 */
public class MediaPlayerManager {
    private static final String TAG = "MediaPlayerManager";
    private static MediaPlayerManager sInstance;

    private SparseArray<ThunderMediaPlayer> mPlayerArray = new SparseArray<>();//用playerId做主键存储
    private SparseArray<MediaPlayerAcceptor> mPlayerAcceptorArray = new SparseArray<>();

    private ThunderMediaPlayer mCurrentMediaPlayer;

    private boolean mIsCanPlayOnMobileNetwork;//在3G网络状态允许播放视频

    private BroadcastReceiver mNetworkObserver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (mIsCanPlayOnMobileNetwork || NetworkHelper.isActiveNetworkWifi(context)) { // 如果在3G网络点击过继续播放或者是WiFi网络，视频直接播放
                return;
            }
            for (int i = 0; i < mPlayerArray.size(); i++) {
                ThunderMediaPlayer mediaPlayer = mPlayerArray.valueAt(i);
                if (mediaPlayer != null && mediaPlayer.getState() != MediaPlayerState.RELEASE && mediaPlayer != mCurrentMediaPlayer) {
                    mediaPlayer.stop();
                    mediaPlayer.reset();
                }
            }
            if (mCurrentMediaPlayer != null && mCurrentMediaPlayer.isPlaying()) {
                mCurrentMediaPlayer.onNetworkChange();
            }
        }
    };

    private MediaPlayerManager() {
        registNetworkObserver();
    }

    public static MediaPlayerManager getInstance() {
        if (sInstance == null) {
            synchronized (MediaPlayerManager.class) {
                if (sInstance == null) {
                    sInstance = new MediaPlayerManager();
                }
            }
        }
        return sInstance;
    }

    public ThunderMediaPlayer applyMediaPlayer(Context context, MediaPlayerAcceptor acceptor) {
        return applyMediaPlayer(context, acceptor, -1);
    }

    private void registNetworkObserver() {
        // 注册接收网络变化的广播
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        AppContext.getInstance().registerReceiver(mNetworkObserver, filter);
    }

    public void unregistNetworkObserver() {
        AppContext.getInstance().unregisterReceiver(mNetworkObserver);
    }

    /**
     * 申请指定PlayerId的MediaPlayer，如果该playerId的MediaPlayer不存在，重新创建一个
     *
     * @param context
     * @param acceptor 用来接收MediaPlayer
     * @param playerId 指定的PlayerId
     * @return
     */
    public ThunderMediaPlayer applyMediaPlayer(Context context, MediaPlayerAcceptor acceptor, int playerId) {
        MLog.debug(TAG,"applyMediaPlayer--id=" + playerId);
        ThunderMediaPlayer player = mPlayerArray.get(playerId);
        player = applyMediaPlayer(context, acceptor, player);
        return player;
    }

    /**
     * 申请指定tag的MediaPlayer，如果该Tag的MediaPlayer不存在，重新创建一个
     *
     * @param context
     * @param acceptor
     * @param tag
     * @return
     */
    public ThunderMediaPlayer applyMediaPlayer(Context context, MediaPlayerAcceptor acceptor, String tag) {
        MLog.debug(TAG,"applyMediaPlayer--tag=" + tag);
        ThunderMediaPlayer player = getMediaPlayerInstanceByTag(tag);
        player = applyMediaPlayer(context, acceptor, player);
        player.setTag(tag);
        return player;
    }

    private ThunderMediaPlayer applyMediaPlayer(Context context, MediaPlayerAcceptor acceptor, ThunderMediaPlayer player) {
        //如果当前播放的player不为空，并且不是当前申请的player，则release
        if(mCurrentMediaPlayer != null && mCurrentMediaPlayer != player){
            releaseMediaPlayer(mCurrentMediaPlayer);
        }
        if (player == null) {
            player = new ThunderMediaPlayer(context);
            mPlayerArray.put(player.getId(), player);
        } else {
            removePlayerAcceptor(player);
            player.setContext(context);
        }
        MLog.debug(TAG,"apply success --player=" + player);
        mPlayerAcceptorArray.put(player.getId(), acceptor);
        acceptor.onPlayerAccept(player);
        mCurrentMediaPlayer = player;
        return player;
    }

    private void removePlayerAcceptor(ThunderMediaPlayer player) {
        MLog.debug(TAG,"removePlayerAcceptor--player=" + player);
        int playerId = player.getId();
        player.removeSelfContainer();
        MediaPlayerAcceptor oldAcceptor = mPlayerAcceptorArray.get(playerId);
        if (oldAcceptor != null) {
            mPlayerAcceptorArray.remove(playerId);
            oldAcceptor.onPlayerRelease(player);
        }
    }

    public void releaseAll() {
        for (int i = 0; i < mPlayerArray.size(); i++) {
            ThunderMediaPlayer mediaPlayer = mPlayerArray.valueAt(i);
            if (mediaPlayer != null) {
                mediaPlayer.release();
            }
        }
        mPlayerArray.clear();
        mPlayerAcceptorArray.clear();
    }

    public boolean handleBackPress() {
        if (mCurrentMediaPlayer == null) {
            return false;
        }
        return mCurrentMediaPlayer.handleBackPress();
    }

//    public void enterFullScreenMode() {
//        if (mCurrentMediaPlayer == null) {
//            return;
//        }
//        mCurrentMediaPlayer.enterFullScreenMode();
//    }
//
//    public void outFullScreenMode() {
//        if (mCurrentMediaPlayer == null) {
//            return;
//        }
//        mCurrentMediaPlayer.outFullScreenMode();
//    }

    public void setCurrentMediaPlayer(ThunderMediaPlayer mediaPlayer) {
        this.mCurrentMediaPlayer = mediaPlayer;
    }

    public void updateCurrentMediaPlayer(String playerTag) {
        this.mCurrentMediaPlayer = null;
        if (TextUtils.isEmpty(playerTag)) {
            return;
        }
        ThunderMediaPlayer mediaPlayer = getMediaPlayerInstanceByTag(playerTag);
        if (mediaPlayer != null) {
            mCurrentMediaPlayer = mediaPlayer;
        }
    }

    public ThunderMediaPlayer getCurrentMediaPlayer() {
        return mCurrentMediaPlayer;
    }

    public void releaseMediaPlayer(String playerTag) {
        MLog.debug(TAG,"releaseMediaPlayer--playerTag=" + playerTag);
        List<ThunderMediaPlayer> mediaPlayers = getMediaPlayerListByTag(playerTag);
        for (ThunderMediaPlayer mediaPlayer : mediaPlayers) {
            releaseMediaPlayer(mediaPlayer);
        }
    }

    public void releaseMediaPlayer(ThunderMediaPlayer mediaPlayer) {
        MLog.debug(TAG,"releaseMediaPlayer--mediaPlayer=" + mediaPlayer);
        if (mediaPlayer == null) {
            return;
        }
        if (mCurrentMediaPlayer == mediaPlayer) {
            mCurrentMediaPlayer = null;
        }
        mediaPlayer.release();
        mPlayerArray.remove(mediaPlayer.getId());
        removePlayerAcceptor(mediaPlayer);
    }

    /**
     * 根据指定的tag获取一个MediaPlayer的实例
     *
     * @param tag
     * @return
     */
    public ThunderMediaPlayer getMediaPlayerInstanceByTag(String tag) {
        if (mCurrentMediaPlayer != null && mCurrentMediaPlayer.getTag().equals(tag)) {
            return mCurrentMediaPlayer;
        }
        int size = mPlayerArray.size();
        for (int i = 0; i < size; i++) {
            ThunderMediaPlayer mediaPlayer = mPlayerArray.valueAt(i);
            if (mediaPlayer.getTag().equals(tag)) {
                return mediaPlayer;
            }
        }
        return null;
    }

    public List<ThunderMediaPlayer> getMediaPlayerListByTag(String tag) {
        List<ThunderMediaPlayer> playerList = new ArrayList<>();
        int size = mPlayerArray.size();
        for (int i = 0; i < size; i++) {
            ThunderMediaPlayer mediaPlayer = mPlayerArray.valueAt(i);
            if (mediaPlayer.getTag().equals(tag)) {
                playerList.add(mediaPlayer);
            }
        }
        return playerList;
    }

    public boolean checkCanPlayAndPromptOnMobileNetwork(final String movieId, final Context context, final MediaPlayerUtils.OnCheckNetworkDialogListener listener) {
        if (mIsCanPlayOnMobileNetwork) { // 如果在3G网络点击过继续播放，视频直接播放
            return true;
        }
        MediaPlayerUtils.showMobileNetNotifyDialog(context, new MediaPlayerUtils.OnCheckNetworkDialogListener() {
            @Override
            public void onLeftBtnClick() {
                mIsCanPlayOnMobileNetwork = false;
                listener.onLeftBtnClick();
            }

            @Override
            public void onRightBtnClick() {
                if (NetworkHelper.isActiveNetworkMobile(context)) {
                    mIsCanPlayOnMobileNetwork = true;
                }
                listener.onRightBtnClick();
            }

            @Override
            public void onBackKeyDown() {
                listener.onBackKeyDown();
            }
        });
        return false;
    }

    public static class PlayerTag {
        public static final String HOME = "home_player";//首页精选页面
        public static final String FEED = "feed_player";//首页短片Feed流
        public static final String CHANNEL = "channel_player";//公众号列表页面
        public static final String SHORT_VIDEO_DETAIL = "short_video_detail_player";//短视频详情页
        public static final String USER = "user";//个人短视频页

    }
}
